/**
 * Copyright (c) 2018 人人开源 All rights reserved.
 *
 * https://www.renren.io
 *
 * 版权所有，侵权必究！
 */

package io.renren.com.qywt.excel.listener;

import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.read.listener.ReadListener;
import io.renren.com.qywt.dto.AftersaleOrderDTO;
import io.renren.com.qywt.excel.AftersaleOrderExcel;
import io.renren.com.qywt.service.AftersaleOrderService;
import io.renren.commons.tools.utils.ConvertUtils;
import io.renren.commons.tools.utils.JsonUtils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.ArrayList;
import java.util.List;


/**
 * Excel模板读取类
 *
 * @author Mark sunlightcs@gmail.com
 */
public class AftersaleOrderExcelListener implements ReadListener<AftersaleOrderExcel> {
    private static final Logger LOGGER = LoggerFactory.getLogger(AftersaleOrderExcelListener.class);
    /**
     * 每隔2000条存储数据库，然后清理list，方便内存回收
     */
    private static final int BATCH_COUNT = 2000;
    private final  List<AftersaleOrderExcel> list = new ArrayList<>();

    /**
     * 通过构造器注入Service
     */
    private final AftersaleOrderService aftersaleOrderService;

    /**
     * 构造方法
     *
     * @param aftersaleOrderService Service对象
     */
    public AftersaleOrderExcelListener(AftersaleOrderService aftersaleOrderService) {
        this.aftersaleOrderService = aftersaleOrderService;
    }
    /**
     * 每条数据解析完，都会调用此方法
     */
    @Override
    public void invoke(AftersaleOrderExcel aftersaleOrderExcel, AnalysisContext context) {
        LOGGER.info("解析到一条数据:{}", JsonUtils.toJsonString(aftersaleOrderExcel));
        if(StringUtils.isNotBlank(aftersaleOrderExcel.getDeliveryNo())){
            list.add(aftersaleOrderExcel);
        }
        // 达到BATCH_COUNT了，需要去存储一次数据库，防止数据几万条数据在内存，容易OOM
        if (list.size() >= BATCH_COUNT) {
            saveData();
            // 存储完成清理 list
            list.clear();
        }
    }

    /**
     * 所有数据解析完成了 都会来调用
     */
    @Override
    public void doAfterAllAnalysed(AnalysisContext context) {
        // 这里也要保存数据，确保最后遗留的数据也存储到数据库
        saveData();
        LOGGER.info("所有数据解析完成！");
    }
    /**
     * 加上存储数据库
     */
    private void saveData() {
        LOGGER.info("{}条数据，开始存储数据库！", list.size());
        aftersaleOrderService.batchImport(list);
        LOGGER.info("存储数据库成功！");
    }

}